package windows;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.swing.DropMode;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.Position;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;

import sqlServer.AppConnection;
import sqlServer.BaseDataObject;
import sqlServer.CreateAppConnectionThread;
import sqlServer.InstalledMenus;
import sqlServer.Menus;
import sqlServer.UpdateThread;
import langBundle.MsgControl;
import com.swtdesigner.SwingResourceManager;
import windowUnits.ActionButtonPane;
import windowUnits.CustomIconRenderer;
import windowUnits.HistoryToolBar;
import windowUnits.ProgressBarThread;
import windowUnits.TreeTransferHandler;
import xml.XmlWebSet;

public class PageContent extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7040603648873591757L;
	private final static String HTMLEDITOR = "Web";
	private final static String MENU = "Menus";
	private final JToolBar toolBar = new JToolBar();
	private JTree tree = null;
	private final JSplitPane splitPane = new JSplitPane();
	private final ActionButtonPane saveItem = new ActionButtonPane();
	private final ActionButtonPane unpublich = new ActionButtonPane();
	private final ActionButtonPane newPage = new ActionButtonPane();
	private final ActionButtonPane removePage = new ActionButtonPane();
	private final ActionButtonPane publishPage = new ActionButtonPane();
	private final JPanel objectsCards = new JPanel(new CardLayout());
	private final JPanel htmlPanel = new JPanel();
	private final JPanel menuPanel = new JPanel();
	private final JLabel pageLabel = new JLabel();
	private final JLabel menuLabel = new JLabel();
	private final JTabbedPane tabbedPaneHtmlEditor = new JTabbedPane();
	private final JTabbedPane tabbedPaneMenuEditor = new JTabbedPane();
	private MsgControl msgBundle = null;
	private CustomIconRenderer treeIconRenderer = new CustomIconRenderer();
	private  Map<Object, String> treeMap = new HashMap<Object, String>();
	private AppConnection applicationConnect;
	private XmlWebSet xmSet;
	private String editedWebPage;
	private ProgressBarThread pg;
	private HashMap <Integer, InstalledMenus> installedMenusMap = new HashMap<Integer, InstalledMenus>();
	private JScrollPane treeScrollPane;
	private MenuEdit menuEdit = null;
	private HistoryToolBar historyToolBar;
	private JPanel statusBarPanel;
	private PageSetup pageSetup = null;
	private SimpleHTMLEditorExample htmlEditor = null;
	
	/**
	 * Create the panel
	 */
	public PageContent(MsgControl msgBundle, XmlWebSet xmSet,String editedWebPage, 
						ProgressBarThread pg, HistoryToolBar historyToolBar,
						JPanel statusBarPanel) {
		super();
		this.msgBundle = msgBundle;
		this.xmSet = xmSet;
		this.editedWebPage = editedWebPage;
		this.pg = pg;
		this.historyToolBar = historyToolBar;
		this.statusBarPanel = statusBarPanel;
		this.menuEdit = new MenuEdit(installedMenusMap,msgBundle);
		this.pageSetup = new PageSetup();
		this.htmlEditor = new SimpleHTMLEditorExample();
		try {
			jbInit();
			applicationConnect = new AppConnection(xmSet,editedWebPage,AppConnection.MYSQL_DB);
			//applicationConnect.setWebPagesStructure(tree, installedMenusMap);
			CreateAppConnectionThread cc = new CreateAppConnectionThread(applicationConnect,pg,installedMenusMap,tree);
			cc.start();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		//
	}
	private void jbInit() throws Exception {
		setLayout(new BorderLayout());
		
		add(toolBar, BorderLayout.NORTH);
		
		toolBar.add(saveItem);
		saveItem.getButton().addActionListener(new saveButtonActionListener());
		saveItem.getButton().setText("Save");
		saveItem.getButton().setIcon(SwingResourceManager.getIcon(NewArticle.class, "/icons/tag.png"));
		msgBundle.setMsgByName(saveItem,"saveItem");
		
		toolBar.add(newPage);
		newPage.getButton().addActionListener(new NewPageButtonActionListener());
		newPage.setButtonAction(new ButtonPreviewActionListener());
		newPage.getButton().setText("New Item");
		newPage.getButton().setIcon(SwingResourceManager.getIcon(NewArticle.class, "/icons/Document33.png"));
		newPage.getButton().setActionCommand("menu");
		msgBundle.setMsgByName(newPage,"newPage");
		
		toolBar.add(removePage);
		removePage.getButton().addActionListener(new RemovePageButtonActionListener());
		removePage.getButton().setText("Delete");
		removePage.getButton().setIcon(SwingResourceManager.getIcon(NewArticle.class, "/icons/stop33.png"));
		msgBundle.setMsgByName(removePage,"removePage");
		
		toolBar.add(unpublich);
		unpublich.getButton().setText("unpublich");
		unpublich.getButton().addActionListener(new unpublichButtonActionListener());
		unpublich.getButton().setIcon(SwingResourceManager.getIcon(NewArticle.class, "/icons/unpublich.png"));
		msgBundle.setMsgByName(unpublich,"unpublich");
		
		toolBar.add(publishPage);
		publishPage.getButton().setText("Publich");
		publishPage.getButton().setIcon(SwingResourceManager.getIcon(NewArticle.class, "/icons/Globe33.png"));
		msgBundle.setMsgByName(publishPage,"publishPage");
		
		add(splitPane);
		
		DefaultMutableTreeNode rootWeb =
            new DefaultMutableTreeNode("Web");
		DefaultMutableTreeNode topMenu = new DefaultMutableTreeNode("Top Menu");
		treeMap.put(topMenu, "-1");
		DefaultMutableTreeNode leftMenu = new DefaultMutableTreeNode("Left Menu");
		treeMap.put(leftMenu, "-1");
		DefaultMutableTreeNode rightMenu = new DefaultMutableTreeNode("Right Menu");
		treeMap.put(rightMenu, "-1");
		
		//rootWeb.add(topMenu);
		//rootWeb.add(leftMenu);
		//rootWeb.add(rightMenu);
		
		treeIconRenderer.setOpenIcon(SwingResourceManager.getIcon(NewArticle.class, "/icons/online.png"));
		treeIconRenderer.setClosedIcon(SwingResourceManager.getIcon(NewArticle.class, "/icons/offline.png"));
		treeIconRenderer.setLeafIcon(SwingResourceManager.getIcon(NewArticle.class, "/icons/online.png"));
		
		tree = new JTree(rootWeb);
		tree.addTreeSelectionListener(new TreeTreeSelectionListener());
		tree.setAutoscrolls(true);
		tree.setDragEnabled(true);
		tree.setDropMode(DropMode.ON_OR_INSERT);
		tree.setTransferHandler(new TreeTransferHandler());
		tree.setCellRenderer(treeIconRenderer);
		
		treeScrollPane = new JScrollPane(tree);
		treeScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		treeScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		splitPane.setLeftComponent(treeScrollPane);
		splitPane.setRightComponent(objectsCards);
		splitPane.setDividerLocation(0.35);
		
		// Web editor
		htmlPanel.setLayout(new BorderLayout());
		htmlPanel.add(pageLabel, BorderLayout.NORTH);
		pageLabel.setHorizontalAlignment(SwingConstants.CENTER);
		pageLabel.setText(editedWebPage);
		
		tabbedPaneHtmlEditor.addTab("Page Setup", null, new PageSetup(), null);
		tabbedPaneHtmlEditor.addTab("Page Edit", null, htmlEditor, null);
		tabbedPaneHtmlEditor.addTab("Page Preview", null, new SimpleWebBrowserExample(), null);
		tabbedPaneHtmlEditor.addTab("Published Page Preview", null, new SimpleWebBrowserExample(), null);		
		htmlPanel.add(tabbedPaneHtmlEditor, BorderLayout.CENTER);
		
		
		// Menu editor
		tabbedPaneMenuEditor.addTab("Menu", null, menuEdit, null);
		menuPanel.setLayout(new BorderLayout());
		menuPanel.add(menuLabel, BorderLayout.NORTH);
		menuLabel.setHorizontalAlignment(SwingConstants.CENTER);
		menuLabel.setText(editedWebPage);
		menuPanel.add(tabbedPaneMenuEditor, BorderLayout.CENTER);
		
		
		objectsCards.add(htmlPanel,HTMLEDITOR);
		objectsCards.add(menuPanel,MENU);
		//tabbedPane.addTab("Page Edit", null, new SimpleHTMLEditorExample(), null);
		//add(new SimpleHTMLEditorExample(),BorderLayout.CENTER);
		//SimpleHTMLEditorExample
	}
	
	private class ButtonPreviewActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			buttonPreview_actionPerformed(e);
		}
	}
	private class unpublichButtonActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			unpublichButton_actionPerformed(e);
		}
	}
	private class saveButtonActionListener implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			saveButton_actionPerformed(arg0);
		}
	}
	private class NewMenuButtonActionListener implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			newMenuButton_actionPerformed(arg0);
		}
	}
	private class RemovePageButtonActionListener implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			removePageButton_actionPerformed(arg0);
		}
	}
	private class NewPageButtonActionListener implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			newPageButton_actionPerformed(arg0);
		}
	}
	private class TreeTreeSelectionListener implements TreeSelectionListener {
		public void valueChanged(TreeSelectionEvent arg0) {
			tree_valueChanged(arg0);
		}
	}
	protected void unpublichButton_actionPerformed(ActionEvent e) {
		JOptionPane.showMessageDialog(this,"Unpublich ");
	}
	protected void buttonPreview_actionPerformed(ActionEvent e) {
	}
	protected void newMenuButton_actionPerformed(ActionEvent arg0) {
		 DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
		 TreePath path = tree.getNextMatch("Web", 0, Position.Bias.Forward);
		 MutableTreeNode node = (MutableTreeNode)path.getLastPathComponent();
		 model.insertNodeInto(new DefaultMutableTreeNode("New Menu"), node, node.getChildCount());
		 
	}
	protected void removePageButton_actionPerformed(ActionEvent arg0) {
		DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
		TreePath path = tree.getSelectionPath();
		MutableTreeNode node = (MutableTreeNode)path.getLastPathComponent();

		try{
			model.removeNodeFromParent(node);
		}catch (Exception e){
			JOptionPane.showMessageDialog(this,"Can't remove: "+e.getMessage());
		}
			
	}
	protected void newPageButton_actionPerformed(ActionEvent arg0) {
		DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
		TreePath path = tree.getSelectionPath();
		DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
		System.out.println(path.toString());
		try{
			if(arg0.getActionCommand().equals("menu")){
			  Menus insMenu = new Menus();
			  insMenu.createNewMenu(applicationConnect,node.getUserObject(),node.getChildCount()+1);
			  DefaultMutableTreeNode insNode = new DefaultMutableTreeNode("Menu "+insMenu.getMenuItem(Menus.MENU_POSITION));
			  insNode.setUserObject(insMenu);
			  model.insertNodeInto(insNode, node, node.getChildCount());
			  javax.swing.tree.TreePath selPath = tree.getPathForRow(node.getChildCount());
			  tree.setSelectionPath(selPath);

			}
		}catch (Exception e){
			JOptionPane.showMessageDialog(this,"Can't insert");
		}
			
	}
	public void closeConnection()  {
		applicationConnect.closeConnection();
        }
	protected void tree_valueChanged(TreeSelectionEvent arg0) {
		TreePath path = arg0.getNewLeadSelectionPath();
		DefaultMutableTreeNode  node = (DefaultMutableTreeNode )path.getLastPathComponent();
		//node
		
		if((node.getUserObject()).getClass().getName().equals("windowUnits.PrimaryWeb")){
			System.out.println("primary web "+path.toString());
			setWebPageToEdit();
		}else if((node.getUserObject()).getClass().getName().equals("sqlServer.Menus")){
			setMenuToEdit((Menus)node.getUserObject());
		}else{
			setWebPageToEdit();
			System.out.println("value changed"+node.toString());
		}
	}
	
	private void setMenuToEdit(Menus menu){
		menuEdit.setMenuToEdit(menu);
		CardLayout cl = (CardLayout)(objectsCards.getLayout());
        cl.show(objectsCards, MENU);
	}
	
	private void setWebPageToEdit(){
		CardLayout cl = (CardLayout)(objectsCards.getLayout());
        cl.show(objectsCards, HTMLEDITOR);
	}
	
	private void unpublishItem(Menus menu){
		menu.setMenu(Menus.PUBLICHED, 0);
		
	}
	
	public void repaintTree(){
		tree.repaint();
	}
	protected void saveButton_actionPerformed(ActionEvent arg0) {
		//DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
		
		//TreePath path = tree.getSelectionPath();
		DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getModel().getRoot();
		updateTreeNodes(node);
		
	}
	
	private void updateTreeNodes(DefaultMutableTreeNode node){
		
		if(((BaseDataObject)node.getUserObject()).isChanged()){
			ProgressBarThread pg = new ProgressBarThread(statusBarPanel,"Update "+((BaseDataObject)node.getUserObject()).getObjectType()+": ");
			pg.start();
			UpdateThread updateMenuThread = new UpdateThread(applicationConnect,pg,tree,node);
			updateMenuThread.start();
			System.out.println("update to db");
		}
		
		Enumeration nodesToUpdate = node.children();
		while(nodesToUpdate.hasMoreElements()){
			updateTreeNodes((DefaultMutableTreeNode)nodesToUpdate.nextElement());
		}
		
	}	
	
}
